import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:mall/components/image_network.dart';
import 'package:mall/components/number_counter.dart';
import 'package:mall/components/product_price.dart';
import 'package:mall/constants.dart';
import 'package:mall/core/models/product_detail.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/pages/store/product_detail_model.dart';
import 'package:mall/core/providers/pages/store/product_option_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/screens/cart/cart_page.dart';
import 'package:mall/screens/group/group_port_screen.dart';
import 'package:mall/screens/order/order_confirm_screen.dart';
import 'package:mall/screens/product/components/product_ad_view.dart';
import 'package:mall/components/count_down_badge.dart';
import 'package:mall/screens/store/store_screen.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 商品详情参数
class ProductPageArgs {
  ProductPageArgs(
    this.aId,
    this.pid,
    this.mId,
    this.referStoreId,
  );

  final int aId;
  final int pid;
  final int mId;
  final int referStoreId;
}

/// 商品详情
class ProductPage extends StatelessWidget {
  static const routeName = '/ProductPage';

  ProductPage({
    Key key,
    @required this.args,
  }) : super(key: key);
  final ProductPageArgs args;

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => ProductDetailModel(
            context.read<Api>(),
            args.aId,
            args.pid,
            args.mId,
            args.referStoreId,
          ),
        )
      ],
      child: Consumer<ProductDetailModel>(
        builder: (context, value, child) {
          switch (value.viewState) {
            case ViewState.busy:
              return Scaffold(
                appBar: child,
                body: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            case ViewState.error:
              return Scaffold(
                appBar: child,
                body: Center(
                  child: Text('${value.errorMessage}'),
                ),
              );
            case ViewState.success:
              return Scaffold(
                body: _BodyWidget(productDetail: value.productDetail),
                bottomNavigationBar: _BottomWidget(productDetail: value.productDetail),
              );
            default:
              return Scaffold(
                appBar: child,
                body: Container(),
              );
          }
        },
        child: AppBar(),
      ),
    );
  }
}

class _BodyWidget extends StatelessWidget {
  final ProductDetail productDetail;

  const _BodyWidget({
    Key key,
    @required this.productDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final mediaQuery = MediaQuery.of(context);
    return CustomScrollView(
      slivers: [
        SliverAppBar(
          leading: IconButton(
            icon: Image.asset('assets/images/all_ic_back_button.png', width: 25),
            onPressed: () => Navigator.of(context).maybePop(),
          ),
          actions: [
            IconButton(
              icon: Image.asset('assets/images/product/ic_cart.png', width: 25),
              onPressed: () => _onCartClicked(context),
            ),
            IconButton(
              icon: Image.asset('assets/images/product/ic_menu.png', width: 25),
              onPressed: () {},
            )
          ],
          flexibleSpace: Stack(
            alignment: Alignment.bottomRight,
            children: [
              _BannerWidget(
                list: productDetail.pictures,
              ),
              ProductAdView(),
              _AreaWidget(
                area: productDetail.storeArea,
                list: productDetail.allArea,
              ),
            ],
          ),
          expandedHeight: mediaQuery.size.width * 0.75,
        ),
        SliverToBoxAdapter(
          child: _ProductDetailWidget(
            productDetail: productDetail,
          ),
        ),
        SliverToBoxAdapter(
          child: Html(
            data: productDetail.product.detail.replaceAll(' src=\"/', ' src=\"$api_base_url/'),
          ),
        )
      ],
    );
  }

  void _onCartClicked(BuildContext context) {
    Navigator.of(context).pushNamed(CartPage.routeName);
  }
}

class _ProductDetailWidget extends StatelessWidget {
  final ProductDetail productDetail;

  const _ProductDetailWidget({
    Key key,
    @required this.productDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          decoration: BoxDecoration(
            color: Theme.of(context).accentColor,
          ),
          height: 50,
          child: Row(
            children: [
              Expanded(
                child: Container(
                  alignment: Alignment.centerLeft,
                  child: Image.asset('assets/images/product/img_hot_sell.png'),
                ),
              ),
              VerticalDivider(
                indent: 10,
                endIndent: 10,
                width: 24,
                thickness: 1,
                color: Colors.white,
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: <Widget>[
                  Text(
                    'e健联特价：',
                    style: TextStyle(color: Colors.white, fontSize: 12),
                  ),
                  if (productDetail.originPrice != '0' &&
                      productDetail.originPrice != productDetail.validPrice.pointCoinString)
                    Text.rich(
                      TextSpan(
                        text: '原价：',
                        style: TextStyle(color: Colors.white, fontSize: 12),
                        children: [
                          TextSpan(
                            text: productDetail.originPrice,
                            style: TextStyle(
                              decoration: TextDecoration.lineThrough,
                            ),
                            children: [
                              TextSpan(
                                text: '￥',
                                style: TextStyle(color: Colors.white),
                              )
                            ],
                          ),
                        ],
                      ),
                    ),
                ],
              ),
              ProductPrice(
                list: productDetail.priceVos,
                color: Colors.white,
                fontSize: 20.sp,
              ),
            ],
          ),
        ),
        Container(
          padding: EdgeInsets.only(
            right: 8,
          ),
          color: Theme.of(context).accentColor,
          child: CountDownBadge(
            startTime: productDetail.startTime,
            endTime: productDetail.endTime,
            serverTime: productDetail.serverTime,
            marginTop: 0,
            fontSize: 18,
          ),
        ),
        Container(
          height: 30,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: <Widget>[
              Expanded(
                child: Text(
                  productDetail.productModelName ?? productDetail.product.name ?? '暂无商品名称',
                  style: TextStyle(fontSize: 16),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              Image.asset('assets/images/product/img_shipping.png', width: 64)
            ],
          ),
        ),
        Divider(height: 4, color: Colors.black54),
        Container(
          height: 30,
          margin: EdgeInsets.symmetric(horizontal: 12),
          child: Row(
            children: <Widget>[
              Image.asset(
                'assets/images/product/ic_indemnity.png',
                width: 12,
              ),
              SizedBox(width: 6),
              Text(
                '服务：正品保证 · 破损包换 · 极速发货',
                style: TextStyle(color: Color(0xFFA9A9A9), fontSize: 12),
              )
            ],
          ),
        ),
        Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(
            color: Colors.white,
          ),
          height: 40,
          child: Text(
            '——  宝贝详情  ——',
            style: TextStyle(fontSize: 15),
          ),
        )
      ],
    );
  }
}

/// Banner
class _BannerWidget extends StatelessWidget {
  final List<Picture> list;

  const _BannerWidget({
    Key key,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Swiper(
      itemBuilder: (context, index) {
        return CachedNetworkImage(
          imageUrl: list[index].url,
          fit: BoxFit.cover,
        );
      },
      itemCount: list.length,
      autoplay: true,
    );
  }
}

/// 所在的商区
class _AreaWidget extends StatelessWidget {
  final PDStoreArea area;
  final List<PDStoreArea> list;

  const _AreaWidget({
    Key key,
    @required this.area,
    @required this.list,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(1),
      decoration: BoxDecoration(
        color: Colors.white.withAlpha(150),
      ),
      margin: EdgeInsets.all(8),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: list
            .map(
              (e) => InkWell(
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  decoration: BoxDecoration(
                    color:
                        area.id == e.id ? Colors.red.withAlpha(150) : Colors.white.withAlpha(150),
                  ),
                  child: Text(
                    "${e.name}",
                    style: TextStyle(
                      color: area.id == e.id ? Colors.white : Colors.black,
                    ),
                  ),
                ),
                onTap: () {
                  /// 切换商区
                  final model = context.read<ProductDetailModel>();
                  Navigator.of(context).pushReplacement(
                    PageRouteBuilder(
                      pageBuilder: (_, __, ___) => ProductPage(
                        args: ProductPageArgs(
                          e.id,
                          model.productDetail.product.id,
                          null,
                          model.referStoreId,
                        ),
                      ),
                      transitionDuration: Duration(seconds: 0),
                    ),
                  );
                },
              ),
            )
            .toList(),
      ),
    );
  }
}

class _BottomWidget extends StatelessWidget {
  final ProductDetail productDetail;

  const _BottomWidget({
    Key key,
    @required this.productDetail,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        padding: EdgeInsets.only(left: 35),
        color: Colors.white,
        height: 52,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            InkWell(
              child: Image.asset(
                'assets/images/product/ic_store.png',
                width: 22,
                color: Theme.of(context).primaryColor,
              ),
              onTap: () {
                _onStoreClicked(context);
              },
            ),
            InkWell(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.shopping_cart,
                    color: Theme.of(context).primaryColor,
                  ),
                  Text(
                    '购物车',
                    style: TextStyle(
                      color: Theme.of(context).primaryColor,
                      fontSize: 10.sp,
                    ),
                  ),
                ],
              ),
              onTap: () => Navigator.of(context).pushNamed(CartPage.routeName),
            ),
            if (!productDetail.defaultMia.enableGroupPurchase)
              Row(
                children: [
                  InkWell(
                    child: Container(
                      alignment: Alignment.center,
                      color: Colors.amber,
                      width: 105,
                      child: Text(
                        '加入购物车',
                        style: TextStyle(color: Colors.white),
                      ),
                    ),
                    onTap: () {
                      _onCartAddClicked(context);
                    },
                  ),
                  SizedBox(
                    width: 105,
                    height: double.infinity,
                    child: RaisedButton(
                      onPressed: () => _pushOrderConfirm(context),
                      elevation: 0,
                      shape: RoundedRectangleBorder(),
                      child: Text('立即购买'),
                    ),
                  ),
                ],
              ),
            if (productDetail.defaultMia.enableGroupPurchase)
              InkWell(
                child: Container(
                  alignment: Alignment.center,
                  color: Colors.red,
                  width: 200,
                  child: Text(
                    productDetail.defaultMia.groupPurchasing ? '拼购中' : '参与拼购',
                    style: TextStyle(color: Colors.white),
                  ),
                ),
                onTap: () {
                  _groupPurchaseQuery(context);
                },
              )
          ],
        ),
      ),
    );
  }

  void _onStoreClicked(BuildContext context) {
    ProductDetailModel model = Provider.of(context, listen: false);
    var storeId = model.productDetail.store.id;
    Navigator.of(context).pushNamed(StoreScreen.routeName, arguments: storeId);
  }

  /// 添加到购物车
  void _onCartAddClicked(BuildContext context) async {
    // 1、选择类型和数量
    final productDetailModel = context.read<ProductDetailModel>();
    final map = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return ChangeNotifierProvider.value(
          value: productDetailModel,
          child: ProductOptionSheet(),
        );
      },
    );
    if (map == null) {
      return;
    }
    final mia = map["mia"] as Mia;
    final quantity = map["quantity"] as int;
    if (mia == null || quantity == null) {
      return;
    }
    // 2、判断商品
    switch (mia.enableGroupPurchase) {
      case true:
        // 提示团购
        final result = await showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text("提示"),
              content: Text("团购商品，是否继续？"),
              actions: [
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  child: Text("确定"),
                ),
              ],
            );
          },
        );
        if (result != null) {
          _doGroupPurchaseQuery(context, mia);
        }
        break;
      default:
        // 3、添加到购物车
        _doCartAdd(context, mia, quantity, productDetailModel.productDetail);
    }
  }

  /// 立即购买
  void _pushOrderConfirm(BuildContext context) async {
    // 1、选择类型和数量
    final productDetailModel = context.read<ProductDetailModel>();
    final map = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return ChangeNotifierProvider.value(
          value: productDetailModel,
          child: ProductOptionSheet(),
        );
      },
    );
    if (map == null) {
      return;
    }
    final mia = map["mia"] as Mia;
    final quantity = map["quantity"] as int;
    if (mia == null || quantity == null) {
      return;
    }
    // 2、判断商品
    switch (mia.enableGroupPurchase) {
      case true:
        // 提示团购
        final result = await showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text("提示"),
              content: Text("团购商品，是否继续？"),
              actions: [
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  child: Text("确定"),
                ),
              ],
            );
          },
        );
        if (result) {
          _doGroupPurchaseQuery(context, mia);
        }
        break;
      default:
        // 3、立即购买
        _doBuyNow(context, mia, quantity, productDetailModel.productDetail);
    }
  }

  /// 当前用户查询拼购窗口信息
  void _groupPurchaseQuery(BuildContext context) async {
    // 1、选择类型和数量
    final productDetailModel = context.read<ProductDetailModel>();
    final map = await showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return ChangeNotifierProvider.value(
          value: productDetailModel,
          child: ProductOptionSheet(),
        );
      },
    );
    if (map == null) {
      return;
    }
    final mia = map["mia"] as Mia;
    final quantity = map["quantity"] as int;
    if (mia == null || quantity == null) {
      return;
    }
    // 2、判断商品
    switch (mia.enableGroupPurchase) {
      case false:
        // 提示普通
        final result = await showDialog(
          context: context,
          builder: (context) {
            return AlertDialog(
              title: Text("提示"),
              content: Text("普通商品，是否继续？"),
              actions: [
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text("取消"),
                ),
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop(true);
                  },
                  child: Text("确定"),
                ),
              ],
            );
          },
        );
        if (result != null) {
          _doBuyNow(context, mia, quantity, productDetailModel.productDetail);
        }
        break;
      default:
        // 3、转到窗口查询页面
        _doGroupPurchaseQuery(context, mia);
    }
  }

  /// 执行添加到购物车
  void _doCartAdd(
    BuildContext context,
    Mia mia,
    int quantity,
    ProductDetail productDetail,
  ) async {
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      await api.cartAdd(
        mia.id,
        quantity,
        productDetail.referStoreId,
      );
      EasyLoading.showToast("已添加到购物车");
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 执行立即购买
  void _doBuyNow(BuildContext context, Mia mia, int quantity, ProductDetail productDetail) async {
    final api = context.read<Api>();
    EasyLoading.show();
    try {
      // 添加到购物车
      final cartAdd = await api.cartAdd(mia.id, quantity, productDetail.referStoreId);
      // 并检查订单
      final cartIdQuantity = {cartAdd.cartId: cartAdd.quantity};
      await api.orderCheck(cartIdQuantity);
      EasyLoading.dismiss();
      // 转到订单确认页面
      Navigator.of(context).pushNamed(
        OrderConfirmScreen.routeName,
        arguments: OrderConfirmScreenArgs(cartIdQuantity),
      );
    } on DioError catch (e) {
      EasyLoading.showToast("${e.message}");
    }
  }

  /// 执行转到窗口查询页面
  void _doGroupPurchaseQuery(BuildContext context, Mia mia) {
    Navigator.of(context).pushNamed(
      GroupPortScreen.routeName,
      arguments: GroupPortScreenArgs(mia.id, productDetail.product.picture),
    );
  }
}

/// 选择商品属性窗口，返回:map keys=(mia,quantity)
class ProductOptionSheet extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        padding: EdgeInsets.fromLTRB(12, 12, 12, 12 + MediaQuery.of(context).viewInsets.bottom),
        child: ChangeNotifierProvider(
          create: (context) => ProductOptionModel(
            context.read<Api>(),
            context.read<ProductDetailModel>(),
          ),
          child: Column(
            children: [
              _MiaInfoWidget(),
              Divider(),
              _OptionListWidget(),
              _QuantityWidget(),
              ProductOptionButton(),
            ],
          ),
        ),
      ),
    );
  }
}

/// 商品所在商区信息
class _MiaInfoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ProductOptionModel>(
      builder: (context, model, child) {
        var sku = model.querySku();
        var mia = model.queryMia();
        return Row(
          children: <Widget>[
            ClipRRect(
              borderRadius: BorderRadius.circular(4),
              child: ImageNetwork(
                url: '${model.productDetail.product.picture}',
                width: 120,
                height: 120,
              ),
            ),
            Expanded(
              child: Container(
                height: 120,
                margin: EdgeInsets.only(left: 16),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    ProductPrice(
                      list: mia.pointCoins,
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 2),
                      child: Text(
                        '库存量：${sku.stock}',
                        style: TextStyle(color: Colors.grey),
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 2),
                      child: Text(
                        '${mia.name}',
                        maxLines: 3,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        );
      },
    );
  }
}

/// 商品可选属性
class _OptionListWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<ProductOptionModel>(
      builder: (context, model, child) {
        var list = model.productDetail.optionList;
        return ListView.builder(
          itemBuilder: (context, index) {
            var option = list[index];
            return Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(option.name),
                  Wrap(
                    spacing: 12,
                    children: List.generate(
                      option.productOptionValues.length,
                      (index) {
                        var optionValue = option.productOptionValues[index];
                        return ChoiceChip(
                          label: Text(optionValue.value),
                          labelPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                          ),
                          onSelected: model.selectable(option, optionValue)
                              ? (values) => model.toggle(option, optionValue)
                              : null,
                          selected: model.selected(option, optionValue),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(4),
                          ),
                        );
                      },
                    ),
                  )
                ],
              ),
            );
          },
          itemCount: model.productDetail.optionList.length,
          shrinkWrap: true,
          physics: NeverScrollableScrollPhysics(),
        );
      },
    );
  }
}

/// 商品数量
class _QuantityWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 8),
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text('购买数量'),
          ),
          Consumer<ProductOptionModel>(
            builder: (context, model, child) {
              return NumberCounter(
                number: model.quantity,
                updateValueChanged: (value) => model.quantity = value,
              );
            },
          ),
        ],
      ),
    );
  }
}

/// 选中属性确定按钮
class ProductOptionButton extends StatelessWidget {
  const ProductOptionButton({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 24),
      child: RaisedButton(
        onPressed: () {
          // 返回选中的属性及数量
          final model = context.read<ProductOptionModel>();
          final map = {"mia": model.queryMia(), "quantity": model.quantity};
          Navigator.of(context).pop(map);
        },
        child: Text("确定"),
      ),
    );
  }
}
